#ifndef SYSTEMTRAYICON_H
#define SYSTEMTRAYICON_H

#include <QAction>
#include <QApplication>
#include <QMenu>
#include <QObject>
#include <QSystemTrayIcon>

class SystemTrayIcon : public QObject
{
    Q_OBJECT
private:
    QWidget *m_parent;
    QMenu *myMenu;
    QAction *maxSizeAction;
    QAction *miniSizeAction;
    QAction *restoreWinAction;
    QAction *quitAction;
    QSystemTrayIcon *myTrayIcon;
public:
    SystemTrayIcon(QWidget *parent)
    {
        m_parent = parent;
        if (QSystemTrayIcon::isSystemTrayAvailable()) // 判断系统是否支持系统托盘图标
        {
            miniSizeAction = new QAction("最小化(&N)", this);
            maxSizeAction = new QAction("最大化(&X)", this);
            restoreWinAction = new QAction("还 原(&R)", this);
            quitAction = new QAction("退出(&Q)", this);
            connect(miniSizeAction, SIGNAL(triggered()), parent, SLOT(hide()));
            connect(maxSizeAction, SIGNAL(triggered()), parent, SLOT(showMaximized()));
            connect(restoreWinAction, SIGNAL(triggered()), parent, SLOT(showNormal()));
            connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

            myMenu = new QMenu((QWidget *)QApplication::desktop());
            myMenu->addAction(maxSizeAction);
            myMenu->addAction(miniSizeAction);
            myMenu->addAction(restoreWinAction);
            myMenu->addSeparator(); // 加入一个分离符
            myMenu->addAction(quitAction);

            myTrayIcon = new QSystemTrayIcon(parent);
            myTrayIcon->setIcon(QIcon(":/img/logo.ico")); // 设置图标图片
            myTrayIcon->setToolTip("我的待办事项");       // 托盘时，鼠标放上去的提示信息
            myTrayIcon->setContextMenu(myMenu);           // 设置托盘上下文菜单
            myTrayIcon->show();
            connect(myTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                          this, SLOT(SystemTrayIconActivated(QSystemTrayIcon::ActivationReason)));
        }
    }

    ~SystemTrayIcon()
    {
        if (QSystemTrayIcon::isSystemTrayAvailable())
        {
            delete myTrayIcon;
            delete myMenu;
            delete quitAction;
            delete restoreWinAction;
            delete maxSizeAction;
            delete miniSizeAction;
        }
    }

public slots:
    void SystemTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
    {
        switch (reason)
        {
        case QSystemTrayIcon::Trigger:
        case QSystemTrayIcon::DoubleClick:
        case QSystemTrayIcon::MiddleClick:
            if (m_parent->isHidden())
                m_parent->showNormal();
            else
                m_parent->hide();
            break;
        default:
            break;
        }
    }
};

#endif // SYSTEMTRAYICON_H
